<template>
 <span
   v-if="richText"
   class="vc-text vc-rich-text"
   :style="style"
   v-html="currValue"
 ></span>
  <span
    v-else
    class="vc-text"
    :style="style"
  >{{ currValue }}</span>
</template>

<script setup>
import {ref, computed, watch, onMounted} from 'vue';
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object,
  inputParam: Object
});
const currNode = ref(props.node);
const currValue = ref('');
const richText = ref(false);

const loadValue = async() => {
  const dataList = (await visual.loadData(
    props.compData,
    {},
    {inputParam: props.inputParam},
    currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  const value = dataList.length > 0 && dataList[0]['内容'] || '文本';
  const compStyle = currNode.value.currCompStyle || {};
  richText.value = compStyle['rich'] || false;
  if (compStyle['formatter'] === 'template') {
    currValue.value = (compStyle['formatterTemplate'] || '')
      .replace('{value}', value || value === 0 ? value : '');
  } else if (compStyle['formatter'] === 'script') {
    try {
      currValue.value = new Function('value', 'return ' + compStyle['formatterScript'])(value);
    } catch (e) {
      console.log('格式化函数解释出错：', e);
    }
  } else {
    currValue.value = value;
  }
};

const style = computed(() => {
  const compStyle = props.compStyle || {};
  let style = visual.parseFontStyle(compStyle);
  if (compStyle['align']) {
    style += `text-align: ${compStyle['align']};`;
  }
  if (compStyle['limitLine']) {
    style += 'display: -webkit-box;' +
      '-webkit-box-orient: vertical;' +
      `-webkit-line-clamp: ${compStyle['limitLine']};` +
      'overflow: hidden;';
  }
  return style;
});

watch(() => props.compStyle, () => {
  loadValue();
}, { deep: true });

watch(() => props.node.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  loadValue();
});
</script>